package news.newsmain.dao;

import news.newsmain.entity.NewsPublish;
import news.util.BaseDao;
import news.util.PageBean;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class MainNewsDaoImpl implements IMainNewsDao {
    private BaseDao baseDao = new BaseDao();

    @Override
    public List<NewsPublish> getNewsPublisList() {
        try {
            baseDao.openDB();
            String sql = "select * from news_publish";
            Statement stmt = baseDao.conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            List<NewsPublish> newsPublisList = new ArrayList<NewsPublish>();
            NewsPublish np = null;
            while(rs.next()){
                np = new NewsPublish();
                np.setTitle(rs.getString("title"));
                np.setId(rs.getInt("id"));
                np.setUserid(rs.getInt("userid"));

                newsPublisList.add(np);
            }
            return newsPublisList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }

    @Override
    public PageBean getNewsPublisPageList(PageBean pageBean) {
        try {
            baseDao.openDB();
            String sql = "select * from news_publish order by id limit ?,?";
            PreparedStatement stmt = baseDao.conn.prepareStatement(sql);
            stmt.setInt(1, pageBean.getStart());
            stmt.setInt(2, pageBean.getPageSize());
            ResultSet rs = stmt.executeQuery();

            List<NewsPublish> newsPublisList = new ArrayList<NewsPublish>();
            NewsPublish np = null;
            while(rs.next()){
                np = new NewsPublish();
                np.setTitle(rs.getString("title"));
                np.setId(rs.getInt("id"));
                np.setUserid(rs.getInt("userid"));

                newsPublisList.add(np);
            }
            pageBean.setObjectList(newsPublisList);
            return pageBean;
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }
    /**
     * @Author GongXL
     * @Description  查询新闻总记录数据
     * @Date 16:50 2022/3/3
     * @Param [news.util.PageBean]
     * @return java.lang.Integer
     **/
    @Override
    public Integer getNewsPublisCount(PageBean pageBean) {
        int count = 0;
        try {
            baseDao.openDB();
            String sql = "select count(1) num from news_publish";
            PreparedStatement stmt = baseDao.conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while(rs.next()){
                count = rs.getInt("num");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return count;
    }

}
